const {merge} = require('webpack-merge')
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin')
const common = require('./webpack.common')

const prodConfig = {
	mode: 'production',
	plugins: [
		new CopyPlugin({
			patterns: [{ from: 'src/banner.txt' }],
		}),
		// new HtmlWebpackPlugin({
		//   templateContent: ({ htmlWebpackPlugin }) => '<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>' + htmlWebpackPlugin.options.title + '</title></head><body><div id=\"app\"></div></body></html>',
		//   filename: 'index.html',
		// }),
		new HtmlWebpackPlugin({
			filename: 'index.html',
			template: 'public/index.html'
		}),
		// new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
		// new LodashModuleReplacementPlugin,
		new BundleAnalyzerPlugin({
			analyzerMode: 'static',
			openAnalyzer: false,
		}),
		new MiniCssExtractPlugin({
			filename: 'css/[name].css'
		}),
		new CleanWebpackPlugin()
	],
	optimization: {
		runtimeChunk: 'single',
		splitChunks: {
			cacheGroups: {
				vendor: {
					test: /[\\/]node_modules[\\/]/,
					name: 'vendors',
					chunks: 'all'
				}
			}
		},
		minimizer: [
			new TerserPlugin({
				parallel: true
			})
		]
	}
};

module.exports = (env, argv) => {
	const config = merge(common(env, argv), prodConfig)
	if (argv.hot) {
		// Cannot use 'contenthash' when hot reloading is enabled.
		config.output.filename = '[name].[hash].js';
	}

	return config;
};